<template>
	<page-body>
		<view class="page">
			<view class="flex benben-position-layout flex flex-wrap align-center talk_flex_0"
				:style="{height:(88+StatusBarRpx)+'rpx',paddingTop:StatusBarRpx+'rpx', }">
				<view class='flex flex-wrap align-center justify-between flex-sub talk_fd0_0'>
					<view class='flex flex-wrap align-center talk_fd0_0_c0'>
						<text class='fu-iconfont2  talk_fd0_0_c0_c0' @tap.stop="handleJumpDiy" data-type="back"
							data-url="1">&#xE794;</text>
					</view>
					<view class='flex flex-wrap align-stretch justify-center'>
						<text class='talk_fd0_0_c1_c0'>历史文件</text>
					</view>
					<view class='flex flex-wrap align-center justify-end talk_fd0_0_c0'>
					</view>
				</view>
			</view>
			<view :style="{height: (88+StatusBarRpx)+'rpx'}"></view>
			<view class="page-content">
				<uni-search-bar placeholder="搜索文件名称" @confirm="search" cancel-button="none"
					style="width:100%;min-width:100%;box-sizing:border-box;">
					<template v-slot:searchIcon>
						<image style="width:28rpx;height:28rpx" src="@/static/talkImage/search.png" />
					</template>
				</uni-search-bar>
				<view class="ite" v-for="ite in fileList" :key="ite.ID"
					@click="download(ite.payload.fileUrl,ite.payload.fileName)">
					<image v-if="getFileSuffix(ite.payload.fileName) == 'pdf'"
						style="width: 80rpx;height: 80rpx;margin-right: 24rpx;" src="@/static/talkImage/typepdf.png"
						mode=""></image>
					<image v-else-if="['xls','xlsx'].includes(getFileSuffix(ite.payload.fileName))"
						style="width: 80rpx;height: 80rpx;margin-right: 24rpx;" src="@/static/talkImage/typetxt.png"
						mode=""></image>
					<image v-else style="width: 80rpx;height: 80rpx;margin-right: 24rpx;"
						src="@/static/talkImage/fileImg.png" mode=""></image>

					<view class="ite-right">
						<view class="name">
							{{ite.payload.fileName}}
						</view>
						<view class="time">
							{{formatTimestampToMD(ite.clientTime)}} · 共1个文件
						</view>
					</view>
				</view>
			</view>
			<view :style="{height: (110+bottomSafeAreaRpx)+'rpx'}"></view>
		</view>
	</page-body>
</template>
<script>
	import uniSearchBar from '@dcloudio/uni-ui/lib/uni-search-bar/uni-search-bar.vue'
	import uniIcons from '@dcloudio/uni-ui/lib/uni-search-bar/uni-search-bar.vue'

	export default {
		data() {
			return {
				groupId: "",
				fileList: [],
				fileListCopy: [],
			}
		},
		components: {
			uniSearchBar,
			uniIcons
		},
		// 小程序页面生命周期，如果是 uni-app 可以写
		onLoad(options) {
			this.groupId = decodeURIComponent(options.groupId)

			this.getFileList()
		},
		computed: {
			// 计算属性
		},
		watch: {
			// 监听器
		},
		methods: {
			search(res) {
				if (!res.value) {
					this.fileList = this.fileListCopy // 如果搜索为空，返回原数组
				} else {
					this.fileList = this.fileListCopy.filter(item => item.payload.fileName.includes(res.value))
				}

			},
			getFileSuffix(fileName) {
				return fileName.split('.').pop(); // 取最后一个点后的内容
			},
			getFileList() {
				console.log('2222222222222', this.groupId)
				let promise = uni.$chat.getMessageList({
					conversationID: 'GROUP' + this.groupId,
				});

				promise.then((imResponse) => {
					this.fileList = imResponse.data.messageList.filter(
						(item) => item.type === 'TIMFileElem'
					);
					this.fileListCopy = this.fileList
					console.log('111111111111111111111111111111', imResponse.data); // 群文件列表
				}).catch((imError) => {
					console.warn('getGroupProfile error:', imError);
				});
			},
			formatTimestampToMD(timestamp) {
				// 注意：10位要 *1000 变成毫秒
				const date = new Date(timestamp * 1000);

				const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始
				const day = date.getDate().toString().padStart(2, '0');

				return `${month}/${day}`;
			},
			download(url1, name1) {
				// #ifdef H5
				// ✅ H5 环境
				fetch(url1, {
						mode: 'cors'
					})
					.then(res => res.blob())
					.then(blob => {
						const a = document.createElement('a')
						const url = window.URL.createObjectURL(blob)
						a.href = url
						a.download = name1
						a.click()
						window.URL.revokeObjectURL(url) // 释放内存
					})
					.catch(err => {
						console.error('H5 下载失败:', err)
					})
				// #endif

				// #ifdef MP-WEIXIN || APP-PLUS
				// ✅ 小程序 / App 环境
				uni.downloadFile({
					url: url1,
					success: (res) => {
						if (res.statusCode === 200) {
							// 保存到本地
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: (saveRes) => {
									console.log('文件已保存:', saveRes.savedFilePath)
									// 打开文件（支持 txt, pdf, word, ppt, xls 等）
									uni.showToast({
										title: '保存成功：' + saveRes.savedFilePath,
										icon: 'none'
									})
								}
							})
						}
					},
					fail: (err) => {
						console.error('小程序/App 下载失败:', err)
					}
				})
				// #endif
			}

		},

		onReady() {},
		onShow() {},
		onHide() {},
		onUnload() {},
	}
</script>
<style lang="scss" scoped>
	.page {
		width: 100vw;
		overflow-x: hidden;
		min-height: calc(100vh - var(--window-bottom));
		background: #fff;
		background-size: 100% auto;

	}

	.page-content {}

	.search {
		height: 64rpx;
		background: #FFFFFF;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		margin: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		background-color: #F5F6F7;
		color: #CCCCCC;
	}

	.ite {
		margin: 36rpx 24rpx 0;
		display: flex;
		align-items: center;
		font-weight: 400;
		font-size: 36rpx;
		color: #333333;

		.ite-right {
			.name {
				font-weight: 400;
				font-size: 32rpx;
				color: #333333;
			}

			.time {
				font-weight: 400;
				font-size: 24rpx;
				color: #999999;
				margin-top: 4rpx;
			}
		}

	}

	.talk_flex_0 {
		background: #fff;
		width: 750rpx;
		height: 88rpx;
		overflow: hidden;
		z-index: 10;
		top: 0rpx;
		background-size: 100% auto !important;
	}

	.talk_fd0_0_c1_c0 {
		font-size: 36rpx;
		font-weight: 700;
		color: #333333;
		line-height: 50rpx;
	}

	.talk_fd0_0_c0_c0 {
		font-size: 36rpx;
		color: #333;
	}

	.talk_fd0_0_c0 {
		width: 120rpx;
	}

	.talk_fd0_0 {
		padding: 0rpx 32rpx 0rpx 32rpx;
	}

	.talk_flex_1 {
		padding: 24rpx;
	}
</style>